package com.safewind.wx.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import com.safewind.wx.util.WxUtil;

public class UserAccessInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 静态资源直接return true
        if (handler instanceof ResourceHttpRequestHandler) {
            return true;
        }

        // 拦截第一次请求，将code转为openId
        // 不拦截login、logout和微信事件
        Object o = request.getSession().getAttribute("openId");
        Object code = request.getParameter("code");
        if (code != null) {
            String openId = null;
            if (o != null) {
                openId = o.toString();
            } else {
                openId = WxUtil.getWebUser(code.toString()).getOpenid();
            }
            if (openId != null) {
                request.getSession().setAttribute("openId", openId);
                String userId = "";// TODO
                if (StringUtils.isBlank(userId)) {
                    request.getSession().setAttribute("prePage", request.getServletPath());
                    request.getRequestDispatcher("/wx/login").forward(request, response);
                    return false;
                } else {
                    request.getSession().setAttribute("userId", userId);
                }
            }
        } else {
            if (o == null) {
                request.getRequestDispatcher("/wx/login").forward(request, response);
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView mav)
            throws Exception {
    }
}
